package swing;

import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

import devices.AbstractDevice;

import annotations.Command;

public class DevicePanel extends JPanel implements ActionListener{ 
	
	Vector<Class<?>> commandClasses = null;
	CommandFrame cf;
	SmartHouseFrame shf;
	int panelIndex;
	AbstractDevice device;
	
	public DevicePanel(AbstractDevice device, SmartHouseFrame shf, int panelIndex){
		
		this.panelIndex=panelIndex;
		this.shf = shf;
		this.device = device;
		Vector<Class<?>> commandClasses=device.getCommands();
		this.commandClasses = commandClasses;
		setLayout(new GridLayout(commandClasses.size(),1));		
		
		for (int i=0;i<commandClasses.size();i++) {
			
			Class<?> commandClass = commandClasses.get(i);
			
			Command annotation = (Command) commandClass.getAnnotation(Command.class);
			String commandName = annotation.name();
			String commandDescription = annotation.description();
			String commandIconURL = annotation.iconURL();		
			
			JButton button = new JButton(commandName);
			button.addActionListener(this);
			button.setActionCommand(i+"");
			button.setToolTipText(commandDescription);
			add(button);
			
		}
		
		setVisible(true);
	}
	
	public void createGui(Class<?> commandClass){
		if (commandClass.getClass().isAnnotationPresent(Command.class))
			throw new RuntimeException("Command not annotated");
		cf = new CommandFrame(commandClass, device);
		shf.displayCommandGui(cf, panelIndex);
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		int index = Integer.parseInt(e.getActionCommand());
		Class<?> commandClass = commandClasses.get(index);
		createGui(commandClass);	
	}

}
